#!/usr/bin/python
# -*- coding:utf-8 -*-
from datetime import datetime

from flask import abort
from flask import g
from flask import json
from flask import render_template
from flask import request
from flask_login import login_required, current_user
from sqlalchemy import desc

from app.actions.blog import blog
from app.database.enums import PUBLISHED_BLOG, TRASH_BLOG, DRAFT_BLOG, BLOG_STATUS_DICT
from app.database.models import Blog, Category, Tag, BlogViews


@blog.route('/', methods=['GET'])
def blog_list():
    query_dict = {
        'author_id': g.default_user.id,
        'is_active': True,
    }

    if not current_user.is_authenticated:
        query_dict['status'] = PUBLISHED_BLOG

    category_id = request.args.get('category_id', None, type=str)
    current_category = None
    if category_id:
        query_dict['category_id'] = category_id
        current_category = Category.query.get(category_id)

    page = request.args.get('page', 1, type=int)
    pagination = Blog.query.filter_by(**query_dict).order_by(desc(Blog.publish_time)).paginate(
        page, per_page=20, error_out=False)

    return render_template('blog/blog_list.html', pagination=pagination,
                           current_category=current_category, BLOG_STATUS_DICT=BLOG_STATUS_DICT)


@blog.route('/<string:blog_suffix>', methods=['GET'])
def blog_detail(blog_suffix):
    current_blog = Blog.query.filter_by(url_suffix=blog_suffix).first()
    if current_blog and (current_user.is_authenticated or (not current_user.is_authenticated and current_blog.status == PUBLISHED_BLOG)):
        blog_id = current_blog.id
        if not current_user.is_authenticated:
            # 增加浏览次数
            BlogViews(blog_id=current_blog.id, ip_address=request.remote_addr).save()
        # 推荐文章
        base_recommend_blog_list = Blog.query.filter(Blog.id != int(blog_id), Blog.category_id ==current_blog.category_id).order_by(desc(Blog.publish_time)).limit(3)
        if base_recommend_blog_list.count() < 3:
            exclude_blog_id_list = [blog_id] + [recommend_blog.id for recommend_blog in base_recommend_blog_list]
            other_blog_list = Blog.query.filter(Blog.id not in exclude_blog_id_list).order_by(desc(Blog.publish_time)).limit(3 - base_recommend_blog_list.count())
            recommend_blog_list = [recommend_blog for recommend_blog in base_recommend_blog_list]
            recommend_blog_list.extend([other_blog for other_blog in other_blog_list])
        else:
            recommend_blog_list = [recommend_blog for recommend_blog in base_recommend_blog_list]
        return render_template('blog/blog_detail.html', **locals())
    else:
        return abort(404)


@blog.route('/edit', methods=['GET', 'POST'])
@login_required
def blog_create():
    if request.method == 'GET':
        query_dict = {
            'is_active': True,
        }
        category_list = Category.query.filter_by(**query_dict)  # 分类列表
        tag_list = Tag.query.filter_by(**query_dict)  # 标签列表
        return render_template('blog/blog_edit.html', category_list=category_list, tag_list=tag_list, PUBLISHED_BLOG=PUBLISHED_BLOG, DRAFT_BLOG=DRAFT_BLOG)
    else:
        res = {'code': 1000}
        blog_title = request.values.get('blog_title')
        blog_content = request.values.get('blog_content')
        blog_md_content = request.values.get('blog_md_content')
        blog_description = request.values.get('blog_description')
        blog_category_id = request.values.get('blog_category_id')
        blog_suffix = request.values.get('blog_suffix')
        blog_tag_id_list = request.values.getlist('blog_tag_id_list[]')
        blog_status = request.values.get('blog_status')
        if blog_title and blog_content and blog_md_content and blog_description and blog_category_id and \
                blog_tag_id_list and blog_suffix:
            new_blog = Blog(title=blog_title, content=blog_content, md_content=blog_md_content,
                            description=blog_description, status=int(blog_status), author_id=g.default_user.id,
                            category_id=blog_category_id, url_suffix=blog_suffix)
            for tag_id in blog_tag_id_list:
                tag = Tag.query.get(int(tag_id))
                new_blog.tags.append(tag)
            if new_blog.status == PUBLISHED_BLOG:
                new_blog.publish_time = datetime.now()
            new_blog.save()
        else:
            res['code'] = 1001
        return json.dumps(res)


@blog.route('/edit/<int:blog_id>', methods=['GET', 'POST'])
@login_required
def blog_edit(blog_id):
    editing_blog = Blog.query.get(int(blog_id))

    if editing_blog:
        if request.method == 'GET':
            editing_blog_tag_list = [tag.id for tag in editing_blog.tags]
            query_dict = {
                'is_active': True,
            }
            category_list = Category.query.filter_by(**query_dict)  # 分类列表
            tag_list = Tag.query.filter_by(**query_dict)  # 标签列表
            return render_template('blog/blog_edit.html', current_blog=editing_blog, category_list=category_list,
                                   tag_list=tag_list, editing_blog_tag_list=editing_blog_tag_list, PUBLISHED_BLOG=PUBLISHED_BLOG, DRAFT_BLOG=DRAFT_BLOG)
        else:
            res = {'code': 1000}
            blog_title = request.values.get('blog_title')
            blog_content = request.values.get('blog_content')
            blog_md_content = request.values.get('blog_md_content')
            blog_description = request.values.get('blog_description')
            blog_category_id = request.values.get('blog_category_id')
            blog_tag_id_list = request.values.getlist('blog_tag_id_list[]')
            blog_status = request.values.get('blog_status')
            blog_suffix = request.values.get('blog_suffix')
            if blog_title and blog_content and blog_md_content and blog_description and blog_tag_id_list and \
                    blog_category_id and blog_status and blog_suffix:
                editing_blog.blog_title = blog_title
                editing_blog.content = blog_content
                editing_blog.md_content = blog_md_content
                editing_blog.description = blog_description
                editing_blog.category_id = blog_category_id
                editing_blog.url_suffix = blog_suffix
                editing_blog.status = int(blog_status)
                editing_blog.tags = []
                for tag_id in blog_tag_id_list:
                    tag = Tag.query.get(int(tag_id))
                    editing_blog.tags.append(tag)
                if editing_blog.status == PUBLISHED_BLOG:
                    editing_blog.publish_time = datetime.now()
                editing_blog.save()
            else:
                res['code'] = 1001
            return json.dumps(res)
    else:
        return abort(404)


@blog.route('/delete/<int:blog_id>', methods=['GET', 'POST'])
@login_required
def blog_delete(blog_id):
    current_blog = Blog.query.get(int(blog_id))
    if current_blog:
        if request.method == 'GET':
            return render_template('blog/blog_delete.html', current_blog=current_blog)
        else:
            res = {'code': 1000}
            current_blog.status = TRASH_BLOG
            current_blog.delete()
            return json.dumps(res)
    else:
        abort(404)